/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.licence;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.util.RsaDecoder;
import com.je.meta.util.RsaOperor;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;

@RpcSchema(schemaId = "txRpcService")
public class TxRpcServiceImpl implements TxRpcService {

    private static final AtomicInteger COUNT = new AtomicInteger(0);
    private static Long lastTime;
    private static final long INTERVAL_TIME = 1000 * 60 * 30;
    private static final int TIMES = 5;

    @Autowired
    private MetaService metaService;
    @Autowired
    private Environment environment;

    @Override
    public JSONObject loadTx() {
        DynaBean deBean = metaService.selectOne("JE_CORE_TABLECOLUMN", ConditionsWrapper.builder()
                .eq("JE_CORE_TABLECOLUMN_ID", "7004da24-65b9-4855-8d56-c06778e9c31d"));
        DynaBean txBean;
        if ("0".equals(deBean.getStr("TABLECOLUMN_REMARK"))) {
            txBean = metaService.selectOne("JE_CORE_TABLECOLUMN", ConditionsWrapper.builder().eq("JE_CORE_TABLECOLUMN_ID", "MnAGsUs67D0sPDhn69v"));
        } else {
            txBean = metaService.selectOne("JE_CORE_TABLECOLUMN", ConditionsWrapper.builder().eq("JE_CORE_TABLECOLUMN_ID", "319fd71e-b5fe-4752-ad43-bf07423613fb"));
        }
        String tx2String = FileUtil.readString(System.getProperty("user.home") + File.separator + ".tmp" + File.separator + "402881e73f85c699013f85de5f1c0011", Charsets.UTF_8);
        String tx3String = FileUtil.readString(System.getProperty("user.home") + File.separator + ".tmp" + File.separator + "402881e53f00d090013f00d83a210047", Charsets.UTF_8);
        JSONObject resultObj = new JSONObject();
        try {
            resultObj.put("a", txBean.getStr("TABLECOLUMN_REMARK"));
            resultObj.put("b", HexUtil.decodeHexStr(tx2String));
            resultObj.put("c", unCompress(new String(Base64.getDecoder().decode(tx3String), Charsets.UTF_8)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultObj;
    }

    @Override
    public JSONObject loadAppTx(String appId) {
        JSONObject resultObj = new JSONObject();
        JSONObject errorInfo = new JSONObject();
        //1.校验appId 是否为空
        if (StringUtil.isEmpty(appId)) {
            errorInfo.put("a", "appId不能为空");
            encrypt(errorInfo, resultObj);
            return resultObj;
        }

        //2.校验appId 是否存在
        DynaBean apkBean = metaService.selectOne("JE_PHONE_APK", ConditionsWrapper.builder().eq("APK_CODE", appId));
        if (apkBean == null) {
            errorInfo.put("a", "找不到对应的apk");
            encrypt(errorInfo, resultObj);
            return resultObj;
        }

        //3.校验文件
        //4.校验文件
        //本地license文件地址
        String folder = environment.getProperty("servicecomb.downloads.directory");
        String licensePath = folder + File.separator + "config" + File.separator + appId + ".license";
        JSONObject dataObj = new JSONObject();
        String content;
        try {
            content = FileUtil.readString(licensePath, Charsets.UTF_8);
            String passResult = cn.hutool.core.codec.Base64.decodeStr(content);
            JSONObject jsonObject = JSONObject.parseObject(passResult);
            resultObj.put("a", jsonObject.getString("a"));
            resultObj.put("b", jsonObject.getString("b"));
            resultObj.put("c", jsonObject.getString("c"));
            resultObj.put("d", jsonObject.getString("d"));
            PrivateKey privateKey = RsaDecoder.generatePrivateKey(jsonObject.getString("d"));
            String nameValue = RsaDecoder.decryptReceivedData(privateKey, passResult);
        } catch (Exception e) {
            errorInfo.put("a", "解密文件失败");
            encrypt(errorInfo, resultObj);
            return resultObj;
        }

        return resultObj;
    }

    @Override
    public boolean pushStatus() {
        boolean flag = false;
        synchronized (TxRpcServiceImpl.class) {
            if (lastTime == null) {
                lastTime = System.currentTimeMillis();
                COUNT.incrementAndGet();
            } else {
                long currentTime = System.currentTimeMillis();
                long interval = currentTime - lastTime;
                if (interval > INTERVAL_TIME && COUNT.get() >= TIMES) {
                    flag = true;
                } else {
                    lastTime = System.currentTimeMillis();
                }
            }
        }
        if (flag) {
            System.exit(0);
        }
        return flag;

    }

    /**
     * 加密错误内容
     *
     * @param errorInfo 需要加密的内容
     * @return
     */
    private void encrypt(JSONObject errorInfo, JSONObject resultObj) {
        Map<String, String> map = Maps.newHashMap();
        //构建加解密对象
        try {
            Map<String, Object> keyMap = RsaOperor.createKeyPairs();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyMap.get("private");
            RSAPublicKey publicKey = (RSAPublicKey) keyMap.get("public");
            String errorResult = RsaOperor.encryptSendData(publicKey, privateKey, errorInfo);
            JSONObject errorJson = JSONObject.parseObject(errorResult);
            resultObj.put("a", errorJson.get("a"));
            resultObj.put("b", errorJson.get("b"));
            resultObj.put("c", errorJson.get("c"));
            resultObj.put("d", errorJson.get("d"));
            //解密
//            RsaOperor.decryptReceivedData(publicKey,privateKey,encrptResult);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
    }

    private static String unCompress(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的 byte 数组输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 创建一个 ByteArrayInputStream，使用 buf 作为其缓冲区数组
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
        // 使用默认缓冲区大小创建新的输入流
        GZIPInputStream gzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n = 0;
        // 将未压缩数据读入字节数组
        while ((n = gzip.read(buffer)) >= 0) {
            // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
            out.write(buffer, 0, n);
        }
        // 使用指定的 charsetName，通过解码字节将缓冲区内容转换为字符串
        return out.toString("UTF-8");
    }
}
